package com.getpebble.android.framework.endpoint;

import android.content.Context;
import android.net.Uri;
import android.text.TextUtils;
import com.getpebble.android.bluetooth.protocol.ProtocolMessage;
import com.getpebble.android.common.core.async.PblAsyncTask;
import com.getpebble.android.common.core.trace.Analytics.MobileAppBehavior;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.framework.install.PutBytesType;
import com.getpebble.android.common.model.FrameworkState;
import com.getpebble.android.common.model.PblDeviceModel;
import com.getpebble.android.framework.endpoint.EndpointRequest.EndpointAction;
import com.getpebble.android.framework.endpoint.EndpointRequest.EndpointArgumentKeys;
import com.getpebble.android.framework.endpoint.PutBytesEndpoint.InstallResult;
import com.getpebble.android.framework.install.Stm32Crc;
import com.getpebble.android.framework.protocol.EndpointId;
import com.google.common.collect.ImmutableSet;
import com.google.common.io.Files;
import com.google.common.primitives.UnsignedInteger;
import com.sun.mail.imap.protocol.ListInfo;
import com.sun.mail.smtp.SMTPMessage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Set;

public class InstallFileEndpoint extends RequestableEndpoint {
    public static final String TAG = InstallFileEndpoint.class.getSimpleName();
    private final Context mContext;
    private String mFileName;
    private FrameworkState mFrameworkState;
    private String mIsoLocale;
    private int mLanguageVersion;
    private final IEndpointMessageSender mMessageSender;
    private final PutBytesEndpoint mPutBytesEndpoint;
    private final Listener mPutBytesEndpointListener = new Listener() {
        public void progressUpdated(UnsignedInteger current, UnsignedInteger max) {
            Trace.debug(InstallFileEndpoint.TAG, "ProgressUpdated; current progress: " + current.intValue());
            InstallFileEndpoint.this.mFrameworkState.setFileInstallProgress(Math.round((current.floatValue() / max.floatValue()) * 100.0f));
        }

        public void transferComplete(UnsignedInteger cookie) {
            Trace.debug(InstallFileEndpoint.TAG, "Transfer complete");
            synchronized (InstallFileEndpoint.this) {
                InstallFileEndpoint.this.mState = State.INSTALLING;
                if (cookie == null) {
                    Trace.debug(InstallFileEndpoint.TAG, "Missing cookie!");
                    InstallFileEndpoint.this.finish(Result.ERROR_FILE_INSTALL_FAILED);
                    return;
                }
                Trace.debug(InstallFileEndpoint.TAG, "Installing file object");
                InstallFileEndpoint.this.mPutBytesEndpoint.install(cookie);
            }
        }

        public void transferFailed(InstallResult installResult) {
            Trace.debug(InstallFileEndpoint.TAG, "Transfer failed");
            InstallFileEndpoint.this.finish(Result.from(installResult));
        }

        public void installComplete(UnsignedInteger cookie) {
            Trace.debug(InstallFileEndpoint.TAG, "Install complete");
            if (InstallFileEndpoint.this.mFileName.equals("lang")) {
                MobileAppBehavior.logLanguagePackInstallSuccess(InstallFileEndpoint.this.mIsoLocale);
                PblDeviceModel.updateLanguageInfo(InstallFileEndpoint.this.mContext.getContentResolver(), InstallFileEndpoint.this.mMessageSender.getDevice(), InstallFileEndpoint.this.mIsoLocale, InstallFileEndpoint.this.mLanguageVersion);
            }
            InstallFileEndpoint.this.finish(Result.SUCCESS);
        }

        public void installFailed(InstallResult installResult) {
            Trace.debug(InstallFileEndpoint.TAG, "Install failed");
            if (InstallFileEndpoint.this.mFileName.equals("lang")) {
                MobileAppBehavior.logLanguagePackInstallFailed(InstallFileEndpoint.this.mIsoLocale);
            }
            InstallFileEndpoint.this.finish(Result.ERROR_FILE_INSTALL_FAILED);
        }
    };
    private State mState = State.IDLE;
    private Uri mUri = null;

    static /* synthetic */ class AnonymousClass3 {
        static final /* synthetic */ int[] $SwitchMap$com$getpebble$android$framework$endpoint$EndpointRequest$EndpointAction = new int[EndpointAction.values().length];
        static final /* synthetic */ int[] $SwitchMap$com$getpebble$android$framework$endpoint$PutBytesEndpoint$InstallResult = new int[InstallResult.values().length];

        static {
            try {
                $SwitchMap$com$getpebble$android$framework$endpoint$PutBytesEndpoint$InstallResult[InstallResult.OK.ordinal()] = 1;
            } catch (NoSuchFieldError e) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$endpoint$PutBytesEndpoint$InstallResult[InstallResult.CANCELLED.ordinal()] = 2;
            } catch (NoSuchFieldError e2) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$endpoint$PutBytesEndpoint$InstallResult[InstallResult.TIMEOUT.ordinal()] = 3;
            } catch (NoSuchFieldError e3) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$endpoint$EndpointRequest$EndpointAction[EndpointAction.ADD_FILE.ordinal()] = 1;
            } catch (NoSuchFieldError e4) {
            }
        }
    }

    public enum Result {
        SUCCESS(0),
        ERROR_PRF(-1),
        ERROR_INSTALL_IN_PROGRESS(-2),
        ERROR_FILE_LOAD(-7),
        ERROR_FILE_INSTALL_FAILED(-10),
        ERROR_TIMEOUT(-12),
        ERROR_NO_CONNECTED_DEVICE(-15),
        ERROR_CANCELLED(-16),
        ERROR_UNKNOWN(-100);
        
        private int mValue;

        private Result(int value) {
            this.mValue = value;
        }

        public int getValue() {
            return this.mValue;
        }

        public static Result fromValue(int value) {
            for (Result result : values()) {
                if (result.getValue() == value) {
                    return result;
                }
            }
            return ERROR_UNKNOWN;
        }

        public static Result from(InstallResult result) {
            if (result == null) {
                return ERROR_FILE_INSTALL_FAILED;
            }
            switch (AnonymousClass3.$SwitchMap$com$getpebble$android$framework$endpoint$PutBytesEndpoint$InstallResult[result.ordinal()]) {
                case SMTPMessage.RETURN_FULL /*1*/:
                    return SUCCESS;
                case SMTPMessage.RETURN_HDRS /*2*/:
                    return ERROR_CANCELLED;
                case ListInfo.INDETERMINATE /*3*/:
                    return ERROR_TIMEOUT;
                default:
                    return ERROR_FILE_INSTALL_FAILED;
            }
        }
    }

    public enum State {
        IDLE,
        SENDING_FILE,
        INSTALLING
    }

    public InstallFileEndpoint(Context context, IEndpointMessageSender messageSender, PutBytesEndpoint putBytesEndpoint) {
        if (context == null) {
            throw new IllegalArgumentException("'context' cannot be null!");
        } else if (messageSender == null) {
            throw new IllegalArgumentException("'messageSender' cannot be null!");
        } else {
            this.mContext = context;
            this.mMessageSender = messageSender;
            this.mPutBytesEndpoint = putBytesEndpoint;
        }
    }

    Set<EndpointId> getSupportedEndpoints() {
        return ImmutableSet.of(EndpointId.FILE_INSTALL_MANAGER);
    }

    private void finish(Result result) {
        Trace.debug(TAG, "Install complete with result: " + result);
        if (this.mFrameworkState != null) {
            this.mFrameworkState.setFileInstallResult(result.getValue(), this.mUri);
        }
        cleanupInstall();
    }

    private synchronized void cleanupInstall() {
        this.mState = State.IDLE;
        this.mUri = null;
        this.mPutBytesEndpoint.unlock(this.mPutBytesEndpointListener);
        this.mFrameworkState = null;
        this.mLanguageVersion = -1;
        this.mIsoLocale = null;
        this.mFileName = null;
    }

    synchronized void addFile(final Uri fileUri, final String fileName) {
        new PblAsyncTask() {
            public boolean doInBackground() {
                return InstallFileEndpoint.this.addFileSync(fileUri, fileName);
            }

            public void onTaskSuccess() {
            }

            public void onTaskFailed() {
            }
        }.submit();
    }

    synchronized boolean addFileSync(Uri fileUri, String fileName) {
        boolean z = false;
        synchronized (this) {
            if (this.mState != State.IDLE) {
                Trace.debug(TAG, "Already installing");
                if (this.mFrameworkState != null) {
                    this.mFrameworkState.setFileInstallResult(Result.ERROR_INSTALL_IN_PROGRESS.getValue(), fileUri);
                }
            } else {
                File file = new File(fileUri.getPath());
                if (file.exists()) {
                    Trace.debug(TAG, "Sending byte data");
                    this.mState = State.SENDING_FILE;
                    this.mUri = fileUri;
                    if (setupPutBytesEndpoint(file, fileName)) {
                        Trace.debug(TAG, "Starting transfer");
                        this.mPutBytesEndpoint.startTransfer();
                        z = true;
                    } else {
                        Trace.error(TAG, "Failed to set up put bytes endpoint");
                        finish(Result.ERROR_FILE_LOAD);
                    }
                } else {
                    Trace.error(TAG, "Failed to open file for URI: " + fileUri);
                    finish(Result.ERROR_FILE_LOAD);
                }
            }
        }
        return z;
    }

    private boolean setupPutBytesEndpoint(File file, String filename) {
        if (file == null) {
            Trace.error(TAG, "No data to create PutBytesEndpoint");
            return false;
        } else if (TextUtils.isEmpty(filename)) {
            Trace.error(TAG, "Filename required");
            return false;
        } else if (this.mPutBytesEndpoint.lock(this.mPutBytesEndpointListener)) {
            try {
                InputStream inputStream = new FileInputStream(file);
                int size = Long.valueOf(file.length()).intValue();
                try {
                    this.mPutBytesEndpoint.setInstallType(PutBytesType.FILE).setInputStream(inputStream).setName(filename).setSize(size).setExpectedCrc(UnsignedInteger.fromIntBits(getCrc(file))).setAppBank(0);
                    return true;
                } catch (IOException e) {
                    try {
                        inputStream.close();
                        return false;
                    } catch (IOException e2) {
                        Trace.debug(TAG, "Error closing input stream", e);
                        return false;
                    }
                }
            } catch (IOException e3) {
                Trace.error(TAG, "Failed to open input stream", e3);
                return false;
            }
        } else {
            Trace.error(TAG, "Failed to register listener with put bytes endpoint");
            return false;
        }
    }

    private int getCrc(File file) throws IOException {
        byte[] fileAsByteArray = Files.toByteArray(file);
        return new Stm32Crc().addBytes(fileAsByteArray, fileAsByteArray.length).finalizeCrc();
    }

    boolean onRequest(EndpointRequest request, FrameworkState frameworkState) {
        Trace.debug(TAG, "Got request: " + request.getAction());
        this.mFrameworkState = frameworkState;
        switch (AnonymousClass3.$SwitchMap$com$getpebble$android$framework$endpoint$EndpointRequest$EndpointAction[request.getAction().ordinal()]) {
            case SMTPMessage.RETURN_FULL /*1*/:
                Uri fileUri = (Uri) request.getParcelable(EndpointArgumentKeys.URI);
                this.mFileName = request.getString(EndpointArgumentKeys.FILE_NAME);
                this.mIsoLocale = request.getString(EndpointArgumentKeys.ISO_LOCALE);
                this.mLanguageVersion = request.getInt(EndpointArgumentKeys.LANGUAGE_VERSION).intValue();
                addFile(fileUri, this.mFileName);
                return true;
            default:
                Trace.debug(TAG, "Got unexpected request: " + request.getAction());
                return false;
        }
    }

    boolean onPrfRequest(EndpointRequest request, FrameworkState frameworkState) {
        this.mFrameworkState = frameworkState;
        switch (AnonymousClass3.$SwitchMap$com$getpebble$android$framework$endpoint$EndpointRequest$EndpointAction[request.getAction().ordinal()]) {
            case SMTPMessage.RETURN_FULL /*1*/:
                Trace.debug(TAG, "Unable to add file in PRF mode");
                finish(Result.ERROR_PRF);
                return true;
            default:
                return false;
        }
    }

    boolean onReceive(ProtocolMessage message) {
        Trace.error(TAG, "Received unsupported, unexpected protocol message " + message.toString());
        return false;
    }
}
